<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="8">
        <el-card style="height: calc(100vh - 130px)">
          <div slot="header">
            <el-select
              v-model="queryParams.institutionCode"
              placeholder="请选择"
              size="small"
              style="width: 240px" @change="handleBidChange"
            >
              <el-option-group
                v-for="group in projectBidOptions"
                :key="group.name"
                :label="group.name">
                <el-option
                  v-for="item in group.bids"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-option-group>
            </el-select>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAddMaster"
                v-hasPermi="['labour:salary:add']"
              >新增</el-button>
            </el-col>
          </el-row>
          <el-table v-loading="loading" border :data="masterList" @cell-click="handleDblclick">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="日期" align="center" prop="salaryDate" />
            <el-table-column label="年" align="center" prop="salaryDateYear" />
            <el-table-column label="月" align="center" prop="salaryDateMonth" />
            <el-table-column label="附件" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-picture"
                  type="primary"
                  size="small"
                  @click="handleAnnex(scope.row)"
                  v-if="scope.row.hasAnnex == 'Y'"
                >
                </el-button>
                <el-button
                  icon="el-icon-picture-outline"
                  size="small"
                  @click="handleAnnex(scope.row)"
                  v-else
                >
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateMaster(scope.row)"
                  v-hasPermi="['labour:salary:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteMaster(scope.row)"
                  v-hasPermi="['labour:salary:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getMasterList"
          />
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card style="height: calc(100vh - 130px)">
          <div slot="header">
            <el-input
              v-model="detailQueryParams.idNo"
              placeholder="身份证号/姓名"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-button slot="append" icon="el-icon-search" @click="handleDetailQuery"></el-button>
            </el-input>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAddDetail"
                v-hasPermi="['labour:salary:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
                v-hasPermi="['labour:salary:import']"
              >导入
              </el-button>
            </el-col>
          </el-row>
          <el-table v-loading="detailLoading" border :data="detailList">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="身份证号" align="center" prop="idNo" />
            <el-table-column label="姓名" align="center" prop="name" />
            <el-table-column label="出勤天数" align="center" prop="attendanceDay" />
            <el-table-column label="应发金额" align="center" prop="totalPayAmount" />
            <el-table-column label="实发金额" align="center" prop="finalPayingAmount" />
            <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateDetail(scope.row)"
                  v-hasPermi="['labour:salary:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteDetail(scope.row)"
                  v-hasPermi="['labour:salary:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="detailTotal>0"
            :total="detailTotal"
            :page.sync="detailQueryParams.pageNum"
            :limit.sync="detailQueryParams.pageSize"
            @pagination="getDetailList"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改主表对话框 -->
    <el-dialog :title="master.title" :visible.sync="master.open" :close-on-click-modal="false" style="margin-top: 150px" width="500px" append-to-body>
      <el-form ref="masterForm" :model="master.form" :rules="master.rules" label-width="80px">

        <el-form-item label="日期" prop="salaryDate">
          <el-date-picker
            v-model="master.form.salaryDate"
            align="right"
            type="month"
            value-format="yyyy-MM"
            placeholder="选择日期" style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改明细对话框 -->
    <el-dialog :title="detail.title" :visible.sync="detail.open" :close-on-click-modal="false" style="margin-top: 100px" width="500px" append-to-body>
      <el-form ref="detailForm" :model="detail.form" :rules="detail.rules" label-width="80px">
        <el-form-item label="姓　　名" prop="staffId" v-if="detail.form.detailId == null">
          <el-select v-model="detail.form.staffId" clearable filterable placeholder="请选择劳务工" style="width: 100%">
            <el-option
              v-for="item in detail.staffOptions"
              :key="item.id"
              :value="item.id"
              :label="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓　　名" v-if="detail.form.detailId != null">
          <el-input v-model="detail.form.remark" :disabled="true" />
        </el-form-item>
        <el-form-item label="出勤天数" prop="attendanceDay">
          <el-input type="number" v-model="detail.form.attendanceDay" @keydown.native="handleKey" placeholder="请输入出勤天数" />
        </el-form-item>
        <el-form-item label="应发工资" prop="totalPayAmount">
          <el-input type="number" v-model="detail.form.totalPayAmount" @keydown.native="handleKey" placeholder="请输入应发工资" />
        </el-form-item>
        <el-form-item label="实发工资" prop="finalPayingAmount">
          <el-input type="number" v-model="detail.form.finalPayingAmount" @keydown.native="handleKey" placeholder="请输入实发工资" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDetailForm">确 定</el-button>
        <el-button @click="cancelDetail">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" :close-on-click-modal="false" style="margin-top: 150px" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&masterId=' + this.detailQueryParams.masterId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 覆盖更新
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="downloadTemplate">下载模板</el-link>
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog :title="result.title" :visible.sync="result.open" :close-on-click-modal="false" width="600px" append-to-body>
      <el-form label-width="68px">
        <el-form-item label="状态">
          <el-select v-model="result.select" placeholder="请选择" @change="handleResultOnChange">
            <el-option
              v-for="item in result.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table :data="result.rows" :height="resultTableHeight" highlight-current-row>
        <el-table-column label="行号" align="center" prop="row" />
        <el-table-column label="内容" align="center" prop="content" width="400" show-overflow-tooltip />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-button size="mini" v-if="scope.row.status=='success'" type="success" icon="el-icon-check" circle></el-button>
            <el-button size="mini" v-if="scope.row.status=='error'" type="danger" icon="el-icon-close" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="result.open = false">关 闭</el-button>
      </div>
    </el-dialog>

    <annex ref="annex"></annex>

  </div>
</template>

<script>

  import { selectProjectBidBranch } from "@/api/project/bid";
  import { detailList, masterList, addMaster, addDetail, getMaster, getDetail, updateMaster, updateDetail, deleteMaster, deleteDetail, downloadTemplate } from "@/api/site/labour/salary";
  import { dropDownListBySalary } from "@/api/site/labour/staff";
  import { getToken } from "@/utils/auth";
  import annex from "@/views/site/labour/salary/annex";

  export default {
    name: "StaffSalary",
    components: { annex },
    data() {
      return {
        resultTableHeight: window.innerHeight - 400,
        // 遮罩层
        loading: false,
        detailLoading: false,
        // 项目标段分组下拉框
        projectBidOptions: [],
        // 表格数据
        masterList: [],
        detailList: [],
        // 选中数组
        ids: [],
        detailIds: [],
        // 总条数
        total: 0,
        detailTotal: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          institutionCode: undefined
        },
        detailQueryParams: {
          pageNum: 1,
          pageSize: 10,
          masterId: undefined,
          idNo: undefined
        },
        master: {
          title: "",
          open: false,
          form: {},
          rules: {
            salaryDate: [
              { required: true, message: "日期不能为空", trigger: "blur" }
            ]
          }
        },
        detail: {
          title: "",
          staffOptions:[],
          open: false,
          form: {},
          rules: {
            staffId: [
              { required: true, message: "姓名不能为空", trigger: "blur" }
            ],
            attendanceDay: [
              { required: true, message: "出勤天数不能为空", trigger: "blur" }
            ],
            totalPayAmount: [
              { required: true, message: "应发工资不能为空", trigger: "blur" }
            ],
            finalPayingAmount: [
              { required: true, message: "实发工资不能为空", trigger: "blur" }
            ],
          }
        },
        // 导入参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 覆盖更新
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { token: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/labour/staff/salary/importData"
        },
        // 导入结果参数
        result: {
          open: false,
          title: "",
          rows: [],
          temp: [],
          select: 'error',
          options: [{
            value: 'all',
            label: '全部'
          },{
            value: 'error',
            label: '异常'
          },{
            value: 'success',
            label: '正常'
          }]
        },
      }
    },
    created() {
      this.initBidSelect();
    },
    methods: {
      /** 初始化标段下拉框 */
      initBidSelect() {
        selectProjectBidBranch().then(response => {
          this.projectBidOptions = response.data;
          if (this.projectBidOptions.length > 0) {
            this.queryParams.institutionCode = this.projectBidOptions[0].bids[0].code;
            this.getMasterList();
          }
        });
      },
      // 标段下拉框发生变化
      handleBidChange() {
        this.queryParams.pageNum = 1;
        this.getMasterList();
        this.detailList = [];
      },
      // 获取工资列表数据
      getMasterList() {
        this.loading = true;
        masterList(this.queryParams).then(response => {
          this.masterList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 主表列双击事件
      handleDblclick(row, column, cell, event) {
        if (column.property == 'salaryDate' || column.property == 'salaryDateYear' || column.property == 'salaryDateMonth') {
          this.detailQueryParams.masterId = row.masterId;
          this.getDetailList();
        }
      },
      /** 搜索按钮操作 */
      handleDetailQuery() {
        this.detailQueryParams.pageNum = 1;
        this.getDetailList();
      },
      // 获取工资明细列表数据
      getDetailList() {
        this.detailLoading = true;
        detailList(this.detailQueryParams).then(response => {
          this.detailList = response.rows;
          this.detailTotal = response.total;
          this.detailLoading = false;
        });
      },
      cancel() {
        this.master.open = false;
        this.reset();
      },
      cancelDetail() {
        this.detail.open = false;
        this.resetDetail();
      },
      // 表单重置
      reset() {
        this.master.form = {
          masterId: null,
          salaryDate: null,
          institutionCode: null,
          salaryDateYear: null,
          salaryDateMonth: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("masterForm");
      },
      resetDetail() {
        this.detail.form = {
          detailId: null,
          masterId: null,
          staffId:null,
          idNo: null,
          battalionId: null,
          teamId: null,
          postId: null,
          attendanceDay: null,
          totalPayAmount: null,
          finalPayingAmount: null,
          arrearsAmount: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        }
      },
      /** 新增按钮操作 */
      handleAddMaster() {
        if (this.queryParams.institutionCode == null) {
          this.$modal.msgError("请先选择项目标段");
          return;
        }
        this.reset();
        this.master.open = true;
        this.master.title = "添加劳务工资发放日期";
      },
      /** 修改按钮操作 */
      handleUpdateMaster(row) {
        this.reset();
        const masterId = row.masterId;
        getMaster(masterId).then(response => {
          this.master.form = response.data;
          this.master.open = true;
          this.master.title = "修改劳务工资发放日期";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["masterForm"].validate(valid => {
          if (valid) {
            if (this.master.form.masterId != null) {
              updateMaster(this.master.form).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.master.open = false;
                this.getMasterList();
              });
            } else {
              this.master.form.institutionCode = this.queryParams.institutionCode;
              addMaster(this.master.form).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.master.open = false;
                this.getMasterList();
                this.detailList = [];
              });
            }
          }
        });
      },
      /** 明细新增按钮操作 */
      handleAddDetail() {
        if (this.detailQueryParams.masterId == null) {
          this.$modal.msgError("请先选择日期");
          return;
        }
        dropDownListBySalary({institutionCode: this.queryParams.institutionCode, masterId: this.detailQueryParams.masterId}).then(response => {
          this.detail.staffOptions = response.staffs;
          this.resetDetail();
          this.detail.open = true;
          this.detail.title = "添加劳务工工资";
        });
      },
      /** 修改明细按钮操作 */
      handleUpdateDetail(row) {
        this.resetDetail();
        const detailId = row.detailId;
        getDetail(detailId).then(response => {
          this.detail.form = response.data;
          this.detail.form.remark = response.data.name + '[' + response.data.idNo + ']';
          this.detail.open = true;
          this.detail.title = "修改劳务工工资";
        });
      },
      /** 提交按钮 */
      submitDetailForm() {
        this.$refs["detailForm"].validate(valid => {
          if (valid) {
            if (this.detail.form.detailId != null) {
              updateDetail(this.detail.form).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.detail.open = false;
                this.getDetailList();
              });
            } else {
              this.detail.form.masterId = this.detailQueryParams.masterId;
              addDetail(this.detail.form).then(response => {
                this.$modal.msgSuccess("操作成功");
                this.detail.open = false;
                this.getDetailList();
              });
            }
          }
        });
      },
      // 删除劳务工工资发放
      handleDeleteMaster(row) {
        const ids = row.masterId;
        this.$modal.confirm('是否确认删除选中的数据项(删除本月所有工资明细)？').then(function() {
          return deleteMaster(ids);
        }).then(() => {
          this.getMasterList();
          this.detailList = [];
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
      },
      // 删除劳务工工资发放明细
      handleDeleteDetail(row) {
        const ids = row.detailId;
        this.$modal.confirm('是否确认删除选中的数据项？').then(function() {
          return deleteDetail(ids);
        }).then(() => {
          this.getDetailList();
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
      },
      // 数据导入
      handleImport() {
        if (this.detailQueryParams.masterId == null) {
          this.$modal.msgError("请先选择日期");
          return;
        }
        this.upload.title = "劳务工工资导入";
        this.result.rows = [];
        this.result.temp = [];
        this.result.select = 'error';
        this.upload.open = true;
      },
      /** 下载模板操作 */
      downloadTemplate() {
        downloadTemplate().then(response => {
          this.$download.name(response.msg);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.$loading().close();
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if (response.rows != undefined) {
          this.result.temp = response.rows;
          response.rows.forEach(e => {
            if (e.status == 'error') {
              this.result.rows.push(e);
            }
          });
        }
        if (response.status == "success") {
          this.getDetailList();
        }
        this.$confirm(response.msg, '导入结果', {
          showCancelButton: true,
          showConfirmButton: response.rows != undefined,
          confirmButtonText: '详情',
          cancelButtonText: '取消',
          type: response.status
        }).then(() => {
          this.result.title = "查看导入详情";
          this.result.open = true;
        }).catch(() => {
        });
      },
      // 导入结果状态发生改变
      handleResultOnChange() {
        if (this.result.select == 'all') {
          this.result.rows = this.result.temp;
        } else if (this.result.select == 'error') {
          this.result.rows = [];
          this.result.temp.forEach(e => {
            if (e.status == 'error') {
              this.result.rows.push(e);
            }
          });
        } else if (this.result.select == 'success') {
          this.result.rows = [];
          this.result.temp.forEach(e => {
            if (e.status == 'success') {
              this.result.rows.push(e);
            }
          });
        }
      },
      // 提交上传文件
      submitFileForm() {
        this.$loading({
          lock: true,
          text: '数据导入中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$refs.upload.submit();
      },
      /** 附件按钮操作 */
      handleAnnex(row) {
        this.$refs.annex.show(row.annexUuid);
      },
      // 禁止输入e
      handleKey(e) {
        let key = e.key
        // 不允许输入'e'
        if (key === 'e') {
          e.returnValue = false
          return false
        }
        return true
      },
    }
  }
</script>

<style lang="scss">
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type='number'] {
    -moz-appearance: textfield;
  }
</style>
